/**
 * 
 */
package instant.mail;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.ImageColumns;

/**
 * @author qiangli
 * 
 */
public class PickImageActivity extends Activity {

	private static final int RC_PICK = 1;
	private static final int DIALOG_SELECT = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		showDialog(DIALOG_SELECT);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_SELECT:
			int checked = Preferences.getBackgroundSelection(this, Preferences.BG_SELECT_SAMPLE_BLUESKEY);
			return new AlertDialog.Builder(this).setTitle(
					R.string.compose_bg_pick_title).setSingleChoiceItems(
					R.array.compose_bg_select_entries, checked,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							doSelect(which);
						}
					}).setCancelable(true).setOnCancelListener(new OnCancelListener() {
						public void onCancel(DialogInterface arg0) {
							finish();
						}
					}).create();
		default:
		}
		return super.onCreateDialog(id);
	}

	private void doSelect(int which) {
		Preferences.putBackgroundSelection(this, which);
		switch (which) {
		case Preferences.BG_SELECT_PHOTO:
			break;
		case Preferences.BG_SELECT_PICK:
			doPick();
			return;
		case Preferences.BG_SELECT_SAMPLE_ANDROID:
			break;
		case Preferences.BG_SELECT_SAMPLE_BLUESKEY:
			break;
		case Preferences.BG_SELECT_SAMPLE_GOODMORNING:
			break;
		case Preferences.BG_SELECT_NO_BACKGROUND:
			break;
		case Preferences.BG_SELECT_GONE_WILD:
			break;
		default:
		}
		finish();
	}

	private void doPick() {
		try {
			Intent i = new Intent(Intent.ACTION_GET_CONTENT);
			i.setType("image/*");
			startActivityForResult(i, RC_PICK);
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			finish();
			return;
		}
		try {
			Uri uri = data.getData();
			if (uri != null) {
				Cursor c = getContentResolver().query(uri,
						new String[] { ImageColumns.DATA }, null, null, null);
				c.moveToFirst();
				String p = c.getString(0);
				c.close();
				Preferences.putBackgroundImagePath(this, p);
			}
		} catch (Exception e) {
			//e.printStackTrace();
		}
		finish();
	}
}
